package com.wtwd.campus.utils;

import com.thoughtworks.xstream.XStream;
import com.wtwd.campus.entity.WxTextMessage;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Wx消息解析
 */
public class WxMessageUtils {

    /**
     * 解析xml信息
     * @param request
     * @return
     */
    public static Map<String,String> xmlToMap(HttpServletRequest request){
        Map<String,String> map=new HashMap<>();
        SAXReader reader=new SAXReader();
        ServletInputStream in =null ;
        try {
            in = request.getInputStream();
            Document doc = reader.read(in);
            Element root = doc.getRootElement();
            List<Element> elements = root.elements();
            elements.stream().forEach(e->{
                map.put(e.getName(),e.getText());
            });
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        } finally {
            if (in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return map;
    }

    /**
     * map转换成xml
     * @param mess
     * @return
     */
    public static String messToXml(WxTextMessage mess){
        XStream xStream=new XStream();
        xStream.alias("xml",WxTextMessage.class);
        return  xStream.toXML(mess);
    }


    /**
     * 获取微信回复消息文本xml
     * @param mess
     * @return
     */
    public static String messToXmlString(WxTextMessage mess){
        return "<xml>\n" +
                "<ToUserName><![CDATA["+mess.getToUserName()+"]]></ToUserName>\n"+
                "<FromUserName><![CDATA["+mess.getFromUserName()+"]]></FromUserName>\n"+
                "<CreateTime>"+mess.getCreateTime()+"</CreateTime>\n" +
                "<MsgType><![CDATA[text]]></MsgType>\n"+
                "<Content><![CDATA["+mess.getContext()+"]]></Content>\n"+
                "</xml>";
    }

}
